#include "parafluidboundingsphere.h"

using namespace ParaFluid;

#include <cmath>
#include <cstdlib>

BoundingSphere::~BoundingSphere()
{
	/* does nothing */
}

BoundingSphere::BoundingSphere()
	: center()
	, radius(0.0)
{
	/* does nothing */
}

BoundingSphere::BoundingSphere(const BoundingSphere & other)
	: center(other.center)
	, radius(other.radius)
{
	/* does nothing */
}

BoundingSphere::BoundingSphere(const Vector & Center, float Radius)
	: center(Center)
	, radius(Radius)
{
	/* does nothing */
}

BoundingSphere::BoundingSphere(const Triangle & triangle)
	: center(
		(triangle.p1.x + triangle.p2.x + triangle.p3.x) / 3.0,
		(triangle.p1.y + triangle.p2.y + triangle.p3.y) / 3.0,
		(triangle.p1.z + triangle.p2.z + triangle.p3.z) / 3.0
	)
	, radius(0.0)
{
	float distance12 = (triangle.p2.x - triangle.p1.x) + (triangle.p2.y - triangle.p1.y) + (triangle.p2.z - triangle.p1.z);
	float distance23 = (triangle.p3.x - triangle.p2.x) + (triangle.p3.y - triangle.p2.y) + (triangle.p3.z - triangle.p2.z);
	float distance31 = (triangle.p1.x - triangle.p3.x) + (triangle.p1.y - triangle.p3.y) + (triangle.p1.z - triangle.p3.z);
	
	if(distance12 < distance23)
	{
		if(distance23 < distance31)
		{
			radius = sqrt(distance31);
		}
		else
		{
			radius = sqrt(distance23);
		}
	}
	else
	{
		if(distance12 < distance31)
		{
			radius = sqrt(distance31);
		}
		else
		{
			radius = sqrt(distance12);
		}
	}
}

BoundingSphere & BoundingSphere::operator= (const BoundingSphere & rhs)
{
	if(&rhs != this)
	{
		center = rhs.center;
		radius = rhs.radius;
	}
	return *this;
}

bool BoundingSphere::contains(const Vector & point) const
{
	bool result = false;
	if(abs(point.x - center.x) <= radius)
	{
		if(abs(point.y - center.y) <= radius)
		{
			if(abs(point.z - center.z) <= radius)
			{
				result = true;
			}
		}
	}
	return result;
}
